package org.linlinjava.litemall.admin.service;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_ACCESSORY_DELETE_NOT_ALLOWED;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_ACCESSORY_NOT_EXIST;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_NAME_EXIST;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_NOT_ALLOW_DELETE;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_NOT_EXIST;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_NOT_PERMISSION;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_NOT_REVIEW;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_PROP_DELETE_NOT_ALLOWED;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_PROP_NOT_EXIST;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_SPEC_DELETE_NOT_ALLOWED;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_SPEC_MER_NOT_EXIST;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_SPEC_NOT_EXIST;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_UPDATE_NOT_ALLOWED;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.linlinjava.litemall.admin.beans.Constants;
import org.linlinjava.litemall.admin.beans.dto.GoodsAccessoryDto;
import org.linlinjava.litemall.admin.beans.dto.GoodsAllinone;
import org.linlinjava.litemall.admin.beans.dto.GoodsMerchandiseDto;
import org.linlinjava.litemall.admin.beans.dto.GoodsProductDto;
import org.linlinjava.litemall.admin.beans.dto.GoodsPropertyDto;
import org.linlinjava.litemall.admin.beans.dto.GoodsReviewDto;
import org.linlinjava.litemall.admin.beans.dto.GoodsSpecAddDto;
import org.linlinjava.litemall.admin.beans.dto.GoodsSpecDto;
import org.linlinjava.litemall.admin.beans.dto.GoodsStatusDto;
import org.linlinjava.litemall.admin.beans.dto.GoodsStoreDto;
import org.linlinjava.litemall.admin.beans.dto.PriceDto;
import org.linlinjava.litemall.admin.beans.enums.AdminGoodsTypeEnum;
import org.linlinjava.litemall.admin.beans.enums.PromptEnum;
import org.linlinjava.litemall.admin.beans.vo.CatVo;
import org.linlinjava.litemall.admin.beans.vo.GoodsPriceVo;
import org.linlinjava.litemall.admin.beans.vo.GoodsRegionVo;
import org.linlinjava.litemall.admin.beans.vo.GoodsVo;
import org.linlinjava.litemall.admin.dto.AdminCategoryIdsDTO;
import org.linlinjava.litemall.admin.errorcode.ErrorCodeConstants;
import org.linlinjava.litemall.admin.vo.AdminGoodsDetailVO;
import org.linlinjava.litemall.core.exception.util.ServiceExceptionUtil;
import org.linlinjava.litemall.core.qcode.QCodeService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.dao.LitemallGoodsLogMapper;
import org.linlinjava.litemall.db.dao.LitemallGoodsMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * 管理产品服务
 *
 * @author yliyun
 * @date 2022/09/14
 */
@Service
public class AdminGoodsService {

    /**
     * 商品服务
     */
    @Autowired
    private LitemallGoodsService goodsService;

    @Resource
    @Lazy
    private LitemallGoodsMapper goodsMapper;

    /**
     * 地区服务
     */
    @Autowired
    private LitemallGoodsRegionService regionService;
    /**
     * 规范服务
     */
    @Autowired
    private LitemallGoodsSpecificationService specificationService;
    /**
     * 规范商品服务
     */
    @Autowired
    private LitemallGoodsSpecificationMerchandiseService specificationMerchandiseService;
    /**
     * 属性服务
     */
    @Autowired
    private LitemallGoodsAttributeService attributeService;
    /**
     * 产品服务
     */
    @Autowired
    private LitemallGoodsProductService productService;
    /**
     * 目录服务
     */
    @Autowired
    private LitemallCategoryService categoryService;
    /**
     * 订单商品服务
     */
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    /**
     * 订单商品配件服务
     */
    @Autowired
    private LitemallOrderGoodsAccessoryService orderGoodsAccessoryService;
    /**
     * 订单产品属性服务
     */
    @Autowired
    private LitemallOrderGoodsPropertyService orderGoodsPropertyService;
    /**
     * 问代码服务
     */
    @Autowired
    private QCodeService qCodeService;
    /**
     * 货物日志服务
     */
    @Autowired
    private LitemallGoodsLogService goodsLogService;
    /**
     * 商品评论服务
     */
    @Autowired
    private GoodsReviewService goodsReviewService;
    /**
     * vip商品服务
     */
    @Autowired
    private LitemallVipGoodsService vipGoodsService;
    /**
     * 货物阶梯价格服务
     */
    @Autowired
    private LitemallGoodsLadderPriceService goodsLadderPriceService;
    /**
     * max -商品价格服务
     */
    @Autowired
    private LitemallGoodsMaxMinusPriceService goodsMaxMinusPriceService;
    /**
     * 车服务
     */
    @Autowired
    private LitemallCartService cartService;
    /**
     * 购物车商品配件服务
     */
    @Autowired
    private LitemallCartGoodsAccessoryService cartGoodsAccessoryService;
    /**
     * 购物车商品房地产服务
     */
    @Autowired
    private LitemallCartGoodsPropertyService cartGoodsPropertyService;
    /**
     * 配件服务
     */
    @Autowired
    private LitemallGoodsAccessoryService accessoryService;
    /**
     * litemall店服务
     */
    @Autowired
    private LitemallShopService litemallShopService;
    /**
     * 店地区服务
     */
    @Autowired
    private LitemallShopRegionService shopRegionService;
    /**
     * litemall地区服务
     */
    @Autowired
    private LitemallRegionService litemallRegionService;
    /**
     * 商品服务
     */
    @Autowired
    private LitemallMerchandiseService merchandiseService;
    /**
     * 商品属性服务
     */
    @Autowired
    private LitemallGoodsPropertyService goodsPropertyService;
    /**
     * litemall商品配件组服务
     */
    @Autowired
    private LitemallGoodsAccessoryGroupService litemallGoodsAccessoryGroupService;

    @Autowired
    private LitemallAdminService litemallAdminService;

    @Autowired
    private LitemallRoleService litemallRoleService;

    /**
     * 商品配方关联表
     */
    @Autowired
    private LumiereGoodsFormulaCorrelationService lumiereGoodsFormulaCorrelationService;

    @Autowired
    private LumierePackageCategoryGoodsService lumierePackageCategoryGoodsService;

    /**
     * 列表
     * 商品列表
     *
     * @param goodsSn    货物sn
     * @param name       名字
     * @param shopId     商店id
     * @param regionId   区域id
     * @param reviewType 检查类型
     * @param page       页面
     * @param limit      限制
     * @param sort       排序
     * @param order      订单
     * @return {@link Object}
     */
    public Object list(String goodsSn, String name, Integer shopId, Integer regionId, Integer reviewType,
                       Integer page, Integer limit, String sort, String order, Integer categoryl3) {
        /*if(shopId!=null){
            //查询门店商品
            List<Map<String, Object>> shops = shopGoodsService.querySelective(goodsSn, name, shopId,
                    page, limit, sort, order);
            List<GoodsVo> goodsVos =  getShopGoodsVos(shops);
            return ResponseUtil.okList(goodsVos, shops);
        }else{*/

        IPage<LitemallGoods> goodsList = goodsService.queryByCondition(goodsSn, name, shopId, regionId, reviewType, page, limit, sort, order, categoryl3);
        if(CollUtil.isEmpty(goodsList.getRecords())){    return ResponseUtil.okPage(goodsList);}
        List<GoodsVo> goodsVos = CollStreamUtil.toList(goodsList.getRecords(),goods->{
            GoodsVo bean = BeanUtil.toBean(goods, GoodsVo.class);
            bean.setSales(orderGoodsService.getGoodsSales(goods.getId(), shopId));
            List<LitemallCategory> categoryHierarchy = categoryService.findCategoryHierarchy(bean.getCategoryId());
            // 通过流遍历并提取分类名称
            String categoryPath = categoryHierarchy.stream()
                    .map(LitemallCategory::getName) // 提取每个分类的名称
                    .collect(Collectors.joining(" / ")); // 连接成 "A/B/C" 格式

            // 设置到 GoodsVo 中
            bean.setCategoryName(categoryPath);
            return bean;
        });
        return ResponseUtil.okPage(goodsList,goodsVos );
    }

    public Object allGoods(Integer shopId) {
        return ResponseUtil.ok(goodsService.filterGoodsByCategoryl3(null));
    }
    public Object filterGoodsByCategoryl3(Integer shopId, Integer categoryl3) {
        LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<LitemallGoods>()
                .eq(categoryl3!=null,LitemallGoods::getCategoryId,categoryl3);
        return ResponseUtil.ok(goodsService.filterGoodsByCategoryl3(lambdaQueryWrapper));
    }

    /**
     * 购物清单
     * 店铺商品列表
     *
     * @param goodsSn    货物sn
     * @param name       名字
     * @param shopId     商店id
     * @param regionId   区域id
     * @param reviewType 检查类型
     * @param page       页面
     * @param limit      限制
     * @param sort       排序
     * @param order      订单
     * @return {@link Object}
     */
    public Object shopList(String goodsSn, String name, Integer shopId, Integer adminId, Integer regionId, Integer reviewType,
                           Integer page, Integer limit, String sort, String order, Integer categoryl3) {
        //店铺商品列表（查询跟店铺同一地区的总部商品和店铺商品）
        List<Integer> goodsIds = getShopGoodsIds(shopId);

        IPage<LitemallGoods> goodsPageList = goodsMapper.selectPage(new Page(page, limit), Wrappers.lambdaQuery(LitemallGoods.class)
                .in(goodsIds.size() > 0, LitemallGoods::getId, goodsIds)
                .eq(reviewType != null, LitemallGoods::getReviewType, reviewType)
                .like(StrUtil.isNotEmpty(goodsSn), LitemallGoods::getGoodsSn, goodsSn)
                .like(StrUtil.isNotEmpty(name), LitemallGoods::getName, name)
                .like(categoryl3 != null, LitemallGoods::getCategoryId, categoryl3)
                .isNull(shopId == null, LitemallGoods::getShopId).orderByDesc(LitemallGoods::getAddTime));

        List goodsVos = CollStreamUtil.toList(goodsPageList.getRecords(),goods->{
            GoodsVo goodsVo = new GoodsVo();
            BeanUtils.copyProperties(goods, goodsVo);
            goodsVo.setSales(orderGoodsService.getGoodsSales(goods.getId(), shopId));
            goodsVo.setEditable(false);
            LitemallCategory category = categoryService.findById(goodsVo.getCategoryId());
            goodsVo.setCategoryName(category.getName());
            return goodsVo;
        });
        //去掉范型重新设置
        goodsPageList.setRecords(goodsVos);
        return ResponseUtil.okPage(goodsPageList);
    }

    //获取门店商品Id集合
    public List<Integer> getShopGoodsIds(Integer shopId){
        if(shopId==null)return CollUtil.newArrayList();
        List<LitemallShopRegion> shopRegions = shopRegionService.queryByShopId(shopId);
        LitemallShopRegion shopRegionCity = shopRegions.get(shopRegions.size() - 1);
        List<LitemallGoodsRegion> goodsRegions = regionService.list(Wrappers.lambdaQuery(LitemallGoodsRegion.class).eq(LitemallGoodsRegion::getCityId, shopRegionCity.getRegionId()));
        return CollStreamUtil.toList(goodsRegions,goodsRegion->goodsRegion.getGoodsId());
    }

    /**
     * 验证
     *
     * @param goodsAllinone 货物allinone
     * @return {@link Object}
     */
    private Object validate(GoodsAllinone goodsAllinone) {
        LitemallGoods goods = goodsAllinone.getGoods();
        String name = goods.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }
        String goodsSn = goods.getGoodsSn();
        if (StringUtils.isEmpty(goodsSn)) {
            return ResponseUtil.badArgument();
        }
        // 分类可以不设置，如果设置则需要验证分类存在
        Integer categoryId = goods.getCategoryId();
        if (categoryId != null && categoryId != 0) {
            if (categoryService.findById(categoryId) == null) {
                return ResponseUtil.badArgumentValue();
            }
        }

        LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        for (LitemallGoodsAttribute attribute : attributes) {
            String attr = attribute.getAttribute();
            if (StringUtils.isEmpty(attr)) {
                return ResponseUtil.badArgument();
            }
            String value = attribute.getValue();
            if (StringUtils.isEmpty(value)) {
                return ResponseUtil.badArgument();
            }
        }

        /**
         GoodsSpecDto[] specifications = goodsAllinone.getSpecifications();
         for (GoodsSpecDto specDto : specifications) {
         String spec = specDto.getSpecification();
         if (StringUtils.isEmpty(spec)) {
         return ResponseUtil.badArgument();
         }
         String value = specDto.getValue();
         if (StringUtils.isEmpty(value)) {
         return ResponseUtil.badArgument();
         }
         }


         LitemallGoodsProduct[] products = goodsAllinone.getProducts();
         for (LitemallGoodsProduct product : products) {
         Integer number = product.getNumber();
         if (number == null || number < 0) {
         return ResponseUtil.badArgument();
         }

         BigDecimal price = product.getSellPrice();
         if (price == null) {
         return ResponseUtil.badArgument();
         }

         // String[] productSpecifications = product.getSpecifications();
         // if (productSpecifications.length == 0) {
         //     return ResponseUtil.badArgument();
         // }
         }
         */

        return null;
    }

    /**
     * 编辑商品
     * <p>
     * TODO
     * 目前商品修改的逻辑是
     * 1. 更新litemall_goods、litemall_goods_product、
     * 2. 逻辑删除litemall_goods_attribute、litemall_goods_ladder_price、litemall_goods_max_minus_price、litemall_vip_goods_price表
     * 3. 添加litemall_goods_attribute、litemall_goods_product、litemall_goods_ladder_price、litemall_goods_max_minus_price、
     * litemall_vip_goods_price表
     * <p>
     * 这里商品5个表的数据采用删除再添加的策略是因为
     * 商品编辑页面，支持管理员添加删除商品规格、添加删除商品属性，因此这里仅仅更新是不可能的，
     * 只能删除5个表旧的数据，然后添加新的数据。
     *
     * @param goodsAllinone 货物allinone
     * @param shopId        商店id
     * @return {@link Object}
     */
    @Transactional(rollbackFor = Exception.class)
    public Object update(GoodsAllinone goodsAllinone, Integer shopId) {
        //更新门店内商品
        Object error = validate(goodsAllinone);
        if (error != null) {
            return error;
        }

        LitemallGoods goods = goodsAllinone.getGoods();
        LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        LitemallVipGoodsPrice vipGoodsPrice = goodsAllinone.getVipPrice();
        LitemallGoodsLadderPrice[] ladderPrices = goodsAllinone.getLadderPrices();
        LitemallGoodsMaxMinusPrice[] maxMinusPrices = goodsAllinone.getMaxMinusPrices();
        LitemallGoodsRegion[] litemallGoodsRegions = goodsAllinone.getRegions();

        Integer id = goods.getId();
        LitemallGoods litemallGoods = goodsService.findById(id);
        if (litemallGoods.getIsOnSale()) {
            return ResponseUtil.fail(GOODS_UPDATE_NOT_ALLOWED, "商品已经上架不能修改");
        }

        //已被添加到购物车的商品不能修改
        /*if (cartService.checkExist(id)) {
            return ResponseUtil.fail(GOODS_UPDATE_NOT_ALLOWED, "商品已经被添加到购物车不能修改");
        }*/
        //将生成的分享图片地址写入数据库
        String url = qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());
        goods.setShareUrl(url);


        // 商品基本信息表litemall_goods
        if (goodsService.updateById(goods) == 0) {
            throw new RuntimeException("更新数据失败");
        }
        saveGoodsLog(goods, Constants.UPDATE_GOODS);
        Integer gid = goods.getId();
        attributeService.deleteByGid(gid);
//        productService.deleteByGid(gid);
        goodsLadderPriceService.deleteByGoodsId(gid);
        goodsMaxMinusPriceService.deleteByGoodsId(gid);
        regionService.deleteByGid(gid);

        if (goods.getPriceType() != 1) {
            vipGoodsService.deleteByGoodsId(goods.getId());
        }

        //添加商品区域
        for (LitemallGoodsRegion goodsRegion : litemallGoodsRegions) {
            goodsRegion.setGoodsId(gid);
            regionService.add(goodsRegion);
        }


        // 商品参数表litemall_goods_attribute
        for (LitemallGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goods.getId());
            attributeService.add(attribute);
        }

        if (null != vipGoodsPrice) {
            if (vipGoodsPrice.getDiamondVipPrice() != null && vipGoodsPrice.getGoldVipPrice() != null || vipGoodsPrice.getPlatinumVipPrice() != null || vipGoodsPrice.getSilverVipPrice() != null) {
                vipGoodsPrice.setGoodsId(goods.getId());
                vipGoodsPrice.setGoodsName(goods.getName());
                vipGoodsService.add(vipGoodsPrice);
            }
        }


        if (null != ladderPrices) {
            for (LitemallGoodsLadderPrice ladderPrice : ladderPrices) {
                if (null != ladderPrice.getNumber() && null != ladderPrice.getPrice()) {
                    ladderPrice.setGoodsId(goods.getId());
                    ladderPrice.setGoodsName(goods.getName());
                    goodsLadderPriceService.add(ladderPrice);
                }
            }
        }

        if (null != maxMinusPrices) {
            for (LitemallGoodsMaxMinusPrice maxMinusPrice : maxMinusPrices) {
                if (null != maxMinusPrice.getMaxPrice() && null != maxMinusPrice.getMinusPrice()) {
                    maxMinusPrice.setGoodsId(goods.getId());
                    maxMinusPrice.setGoodsName(goods.getName());
                    goodsMaxMinusPriceService.add(maxMinusPrice);
                }
            }
        }


        return ResponseUtil.ok();
    }

    /**
     * 删除
     *
     * @param goods  货物
     * @param shopId 商店id
     * @return {@link Object}
     */
    @Transactional
    public Object delete(LitemallGoods goods, Integer shopId) {
        //门店删除商品
//        if(!ObjectUtils.isEmpty(shopId)){
//            shopGoodsService.deleteById(goods.getId());
//            return ResponseUtil.ok();
//        }
        Integer id = goods.getId();
        if (id == null) {
            return ResponseUtil.badArgument();
        }
        LitemallGoods litemallGoods = goodsService.findById(id);
        if (litemallGoods.getIsOnSale()) {
            return ResponseUtil.fail(GOODS_NOT_ALLOW_DELETE, "商品已经上架，不允许删除");
        }

        Integer gid = goods.getId();
        saveGoodsLog(goods, Constants.DELETE_GOODS);
        goodsService.deleteById(gid);
        regionService.deleteByGid(gid);
        specificationService.deleteByGid(gid);
        specificationMerchandiseService.deleteByGid(gid);
        attributeService.deleteByGid(gid);
        productService.deleteByGid(gid);
        goodsLadderPriceService.deleteByGoodsId(gid);
        goodsMaxMinusPriceService.deleteByGoodsId(gid);
        vipGoodsService.deleteByGoodsId(gid);
        accessoryService.deleteByGoodsId(gid);

        lumiereGoodsFormulaCorrelationService.remove(Wrappers.lambdaUpdate(LumiereGoodsFormulaCorrelation.class)
                .eq(LumiereGoodsFormulaCorrelation::getGoodsId,id));

        //套餐关联
        List<LumierePackageCategoryGoods> packageCategoryGoodsList = lumierePackageCategoryGoodsService.list(Wrappers.lambdaQuery(LumierePackageCategoryGoods.class)
                .eq(LumierePackageCategoryGoods::getGoodsId, gid));
        if(packageCategoryGoodsList.size()>0){
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.LUMIERE_PACKAGE_CATEGORY_GOODS_ERROR_IN_USE);
        }

        return ResponseUtil.ok();
    }

    /**
     * 创建
     *
     * @param goodsAllinone 货物allinone
     * @param shopId        商店id
     * @return {@link Object}
     */
    @Transactional(rollbackFor = Exception.class)
    public Object create(GoodsAllinone goodsAllinone, Integer shopId) {
        Object error = validate(goodsAllinone);
        if (error != null) {
            return error;
        }

        LitemallGoods goods = goodsAllinone.getGoods();
        LitemallGoodsAttribute[] attributes = goodsAllinone.getAttributes();
        LitemallGoodsProduct[] products = goodsAllinone.getProducts();
        LitemallGoodsRegion[] litemallGoodsRegions = goodsAllinone.getRegions();

        String name = goods.getName();
        if (shopId != null) {
            goods.setShopId(shopId);
            LitemallShop shop = litemallShopService.getInfoById(shopId);
            goods.setShopName(shop.getName());

            //设置商品类型--店铺商品
            goods.setType(AdminGoodsTypeEnum.P_1.getCode().byteValue());
        } else {
            //设置商品类型--总部商品
            goods.setType(AdminGoodsTypeEnum.P_0.getCode().byteValue());
        }

        if (goodsService.checkExistByName(shopId, name)) {
            return ResponseUtil.fail(GOODS_NAME_EXIST, "此门店商品名已经存在");
        }

        // 商品基本信息表litemall_goods
        goodsService.add(goods);
        saveGoodsLog(goods, Constants.CREATE_GOODS);
        //将生成的分享图片地址写入数据库
        String url = qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());

        Integer goodsId = goods.getId();
        //总部商品时
        //添加商品区域
        for (LitemallGoodsRegion goodsRegion : litemallGoodsRegions) {
            goodsRegion.setGoodsId(goodsId);
            regionService.add(goodsRegion);
        }


        if (!StringUtils.isEmpty(url)) {
            goods.setShareUrl(url);
            if (goodsService.updateById(goods) == 0) {
                throw new RuntimeException("更新数据失败");
            }
        }


        // 商品参数表litemall_goods_attribute
        for (LitemallGoodsAttribute attribute : attributes) {
            attribute.setGoodsId(goodsId);
            attributeService.add(attribute);
        }


        LitemallGoodsProduct product = new LitemallGoodsProduct();
        product.setShopId(shopId);
        product.setGoodsId(goods.getId());
        product.setUnit(goods.getUnit());
        product.setSellPrice(goods.getRetailPrice());
        product.setCostPrice(goods.getCounterPrice());
        productService.add(product);
        return ResponseUtil.ok(goods);
    }

    /**
     * 日志保存货物
     *
     * @param goods   货物
     * @param content 内容
     */
    private void saveGoodsLog(LitemallGoods goods, String content) {
        LitemallGoods litemallGoods = goodsService.findById(goods.getId());
        GoodsReviewDto goodsReviewDto = new GoodsReviewDto();
        goodsReviewDto.setId(goods.getId());
        goodsReviewDto.setGoodsName(litemallGoods.getName());
        goodsReviewDto.setGoodsSn(litemallGoods.getGoodsSn());
        goodsReviewDto.setContent(content + litemallGoods.getName());
        goodsReviewService.saveLog(goodsReviewDto, null);
    }

    /**
     * 用于
     *
     * @return {@link Object}
     */
    public Object list2() {
        // http://element-cn.eleme.io/#/zh-CN/component/cascader
        // 管理员设置“所属分类”
        List<LitemallCategory> l1CatList = categoryService.queryL1();
        List<CatVo> categoryList = new ArrayList<>(l1CatList.size());

        for (LitemallCategory l1 : l1CatList) {
            CatVo l1CatVo = new CatVo();
            l1CatVo.setValue(l1.getId());
            l1CatVo.setLabel(l1.getName());

            List<LitemallCategory> l2CatList = categoryService.queryByPid(l1.getId());
            List<CatVo> children = new ArrayList<>(l2CatList.size());
            for (LitemallCategory l2 : l2CatList) {
                CatVo l2CatVo = new CatVo();
                l2CatVo.setValue(l2.getId());
                l2CatVo.setLabel(l2.getName());
                children.add(l2CatVo);

                List<LitemallCategory> l3CatList = categoryService.queryByPid(l2.getId());
                List<CatVo> c3 = new ArrayList<>(l3CatList.size());
                for (LitemallCategory l3 : l3CatList) {
                    CatVo l3CatVo = new CatVo();
                    l3CatVo.setValue(l3.getId());
                    l3CatVo.setLabel(l3.getName());
                    c3.add(l3CatVo);
                }
                l2CatVo.setChildren(c3);
            }
            l1CatVo.setChildren(children);

            categoryList.add(l1CatVo);
        }


        Map<String, Object> data = new HashMap<>();
        data.put("categoryList", categoryList);
        return ResponseUtil.ok(data);
    }

    /**
     * 查询规范细节
     * 查询商品的规格详情
     *
     * @param gid gid
     * @return {@link List}<{@link GoodsSpecDto}>
     */
    private List<GoodsSpecDto> querySpecDetail(Integer gid) {
        List<GoodsSpecDto> goodsSpecDtos = new ArrayList();

        List<LitemallGoodsSpecification> specifications = specificationService.queryByGid(gid);
        for (LitemallGoodsSpecification litemallGoodsSpecification : specifications) {
            GoodsSpecDto goodsSpecDto = new GoodsSpecDto();
            BeanUtils.copyProperties(litemallGoodsSpecification, goodsSpecDto);

            Integer specId = litemallGoodsSpecification.getId();
            List<LitemallGoodsSpecificationMerchandise> specMerchandises = specificationMerchandiseService.queryBySpecid(specId);
            List<GoodsMerchandiseDto> merchandises = new ArrayList<>();
            for (LitemallGoodsSpecificationMerchandise specificationMerchandise : specMerchandises) {
                GoodsMerchandiseDto goodsMerchandiseDto = new GoodsMerchandiseDto();
                goodsMerchandiseDto.setId(specificationMerchandise.getId());
                goodsMerchandiseDto.setGoodsId(specificationMerchandise.getGoodsId());
                goodsMerchandiseDto.setGoodsSpecificationId(specificationMerchandise.getGoodsSpecificationId());
                goodsMerchandiseDto.setNumber(specificationMerchandise.getNumber());
                goodsMerchandiseDto.setConsumeRatio(specificationMerchandise.getConsumeRatio());
                goodsMerchandiseDto.setModel(specificationMerchandise.getModel());
                Integer merchandiseId = specificationMerchandise.getMerchandiseId();
                goodsMerchandiseDto.setMerchandiseId(merchandiseId);
                setMerchandiseDetail(goodsMerchandiseDto, merchandiseId);

                merchandises.add(goodsMerchandiseDto);
            }
            goodsSpecDto.setMerchandises(merchandises);
            goodsSpecDtos.add(goodsSpecDto);
        }

        return goodsSpecDtos;
    }

    /**
     * 查询附件细节
     *
     * @param gid gid
     * @return {@link List}<{@link GoodsAccessoryDto}>
     */
    private List<GoodsAccessoryDto> queryAccessoryDetail(Integer gid) {
        List<GoodsAccessoryDto> goodsAccessoryDtos = new ArrayList();
        List<LitemallGoodsAccessory> accessories = accessoryService.queryByGoodsId(gid);
        for (LitemallGoodsAccessory litemallGoodsAccessory : accessories) {
            GoodsAccessoryDto goodsAccessoryDto = new GoodsAccessoryDto();
            BeanUtils.copyProperties(litemallGoodsAccessory, goodsAccessoryDto);
            LitemallMerchandise merchandise = merchandiseService.findById(litemallGoodsAccessory.getMerchandiseId());
            goodsAccessoryDto.setBasicUnit(ObjectUtil.isNotNull(merchandise) ? merchandise.getBasicUnit() : "");
            goodsAccessoryDtos.add(goodsAccessoryDto);
        }
        return goodsAccessoryDtos;
    }

    /**
     * 设置商品细节
     *
     * @param goodsMerchandiseDto 货物商品dto
     * @param merchandiseId       商品id
     */
    private void setMerchandiseDetail(GoodsMerchandiseDto goodsMerchandiseDto, Integer merchandiseId) {
        LitemallMerchandise merchandise = merchandiseService.findById(merchandiseId);
        //TODO 添加了空判
        if (ObjectUtil.isNotNull(merchandise)) {
            merchandise.setModel(goodsMerchandiseDto.getModel());
        }
        if (ObjectUtil.isNotNull(merchandise)) {
            merchandiseService.updateById(merchandise);
            goodsMerchandiseDto.setMerchandiseName(merchandise.getName());
            goodsMerchandiseDto.setMerchandiseSn(merchandise.getMerchandiseSn());
            goodsMerchandiseDto.setModel(merchandise.getModel());
            goodsMerchandiseDto.setStandard(merchandise.getStandard());
            goodsMerchandiseDto.setBasicUnit(merchandise.getBasicUnit());
        }
    }

    /**
     * 查询货物区域细节
     *
     * @param goodsId 商品id
     * @return {@link List}<{@link GoodsRegionVo}>
     */
    private List<GoodsRegionVo> queryGoodsRegionDetail(Integer goodsId) {
        List<GoodsRegionVo> result = new ArrayList<>();
        List<LitemallGoodsRegion> regions = regionService.queryByGid(goodsId);
        for (LitemallGoodsRegion goodsRegion : regions) {
            GoodsRegionVo goodsRegionVo = new GoodsRegionVo();
            BeanUtils.copyProperties(goodsRegion, goodsRegionVo);
            result.add(goodsRegionVo);
        }
        return result;
    }

    /**
     * 细节
     *
     * @param id id
     * @return {@link Object}
     */
    public Object detail(Integer id) {
        LitemallGoods goods = goodsService.findById(id);
        List<LitemallGoodsProduct> products = productService.queryByGid(id);
        List<GoodsSpecDto> goodsSpecDtos = querySpecDetail(id);
        List<LitemallGoodsAttribute> attributes = attributeService.queryByGid(id);
        LitemallVipGoodsPrice vipGoodsPrice = vipGoodsService.queryByGoodsId(id);
        List<LitemallGoodsLadderPrice> ladderPrices = goodsLadderPriceService.queryByGoodsId(id);
        List<LitemallGoodsMaxMinusPrice> maxMinusPrices = goodsMaxMinusPriceService.queryByGoodsId(id);
        List<GoodsAccessoryDto> goodsAccessoryDtos = queryAccessoryDetail(id);
        List<LitemallGoodsProperty> goodsProperties = goodsPropertyService.queryByGoodsId(id);

        List<GoodsRegionVo> regions = queryGoodsRegionDetail(id);

        Integer categoryId = goods.getCategoryId();
        LitemallCategory category = categoryService.findById(categoryId);
        Integer[] categoryIds = new Integer[]{};
        if (category != null) {
            Integer parentCategoryId = category.getPid();
            LitemallCategory c2 = categoryService.findById(parentCategoryId);
            categoryIds = new Integer[]{c2.getPid(), parentCategoryId, categoryId};
        }
        AdminGoodsDetailVO adminGoodsDetailVO = AdminGoodsDetailVO.builder()
                .goods(goods)
                .specifications(goodsSpecDtos)
                .products(products)
                .attributes(attributes)
                .categoryIds(categoryIds)
                .vipGoodsPrice(vipGoodsPrice)
                .ladderPrices(ladderPrices)
                .maxMinusPrices(maxMinusPrices)
                .accessories(goodsAccessoryDtos)
                .regions(regions)
                .properties(goodsProperties)
                .build();

        return ResponseUtil.ok(adminGoodsDetailVO);
    }

    /**
     * 日志查询商品列表
     * 商品日志列表
     *
     * @param goodsId   商品id
     * @param goodsName 商品名称
     * @param goodsSn   货物sn
     * @param userName  用户名
     * @param content   内容
     * @param page      页面
     * @param limit     限制
     * @param sort      排序
     * @param order     订单
     * @return {@link Object}
     */
    public Object queryGoodsLogList(Integer goodsId, String goodsName, String goodsSn, String userName, String content, Integer page,
                                    Integer limit, String sort, String order) {
        return ResponseUtil.okPage(goodsLogService.querySelective(goodsId, goodsName, goodsSn, userName, content, page, limit, sort, order));
    }

    /**
     * 更新货物状态
     * 修改商品上架、推荐、新品
     *
     * @param goodsStatusDto 货物状态dto
     * @param shopId         商店id
     * @return {@link Object}
     */
    @Transactional
    public Object updateGoodsStatus(GoodsStatusDto goodsStatusDto, Integer shopId) {
        LitemallGoods goods = new LitemallGoods();
        goods.setId(goodsStatusDto.getId());

        // 处理是否热门
        Boolean isHot = goodsStatusDto.getIsHot();
        if (isHot != null) {
            saveGoodsLog(goods, isHot ? Constants.GOODS_COMMENTED : Constants.GOODS_COMMENTED_NOT);
            goods.setIsHot(isHot);
        }

        // 处理是否新品
        Boolean isNew = goodsStatusDto.getIsNew();
        if (isNew != null) {
            saveGoodsLog(goods, isNew ? Constants.GOODS_NEW : Constants.GOODS_NEW_NOT);
            goods.setIsNew(isNew);
        }

        // 处理是否上架
        Boolean isOnSale = goodsStatusDto.getIsOnSale();
        if (isOnSale != null) {
            if (isOnSale) {
                LitemallGoods litemallGoods = goodsService.findById(goodsStatusDto.getId());
                if (litemallGoods.getReviewType() != Constants.GOODS_REVIEW_APPROVE.byteValue()) {
                    return ResponseUtil.fail(GOODS_NOT_REVIEW, "商品尚未审核，不能上架");
                }

                List<LumiereGoodsFormulaCorrelation> goodsFormulaCorrelations = lumiereGoodsFormulaCorrelationService.list(Wrappers.lambdaQuery(LumiereGoodsFormulaCorrelation.class)
                        .eq(LumiereGoodsFormulaCorrelation::getGoodsId, goodsStatusDto.getId()));

                if(CollectionUtils.isEmpty(goodsFormulaCorrelations)){
                    // 查询规格列表
                    List<LitemallGoodsSpecification> specs = specificationService.queryByGid(goodsStatusDto.getId());
                    if (CollectionUtils.isEmpty(specs)) {
                        return ResponseUtil.fail(GOODS_SPEC_NOT_EXIST, "商品未配置规格，不能上架");
                    }

                    // 查询规格是否配置辅料
                    for (LitemallGoodsSpecification goodsSpecification : specs) {
                        List<LitemallGoodsSpecificationMerchandise> specMerchandises = specificationMerchandiseService.queryBySpecid(goodsSpecification.getId());
                        if (CollectionUtils.isEmpty(specMerchandises)) {
                            return ResponseUtil.fail(GOODS_SPEC_MER_NOT_EXIST, "存在商品规格未配置原料，不能上架");
                        }
                    }
                }

                saveGoodsLog(goods, Constants.GOODS_PUSH);
            } else {
                saveGoodsLog(goods, Constants.GOODS_PUSH_NOT);

                /*// 商品下架，检查购物车
                List<LitemallCart> carts = cartService.checkGoods(goods.getId());
                carts.forEach(cart -> {
                    cart.setDeleted(true);
                    cartService.updateById2(cart);
                });*/
            }
            goods.setIsOnSale(isOnSale);
        }

        // 更新商品信息
        if (shopId != null) {
            goods.setShopId(shopId);
            goodsService.updateByIdAndShop(goods);
        } else {
            goodsService.updateById(goods);
        }
        return ResponseUtil.ok();
    }


    /**
     * 更新产品价格
     * 修改商品价格
     *
     * @param price  价格
     * @param shopId 商店id
     * @return {@link Object}
     */
    public Object updateGoodsPrice(PriceDto price, Integer shopId) {
        LitemallGoods goods = goodsService.findById(price.getId());
        if (null == goods) {
            return ResponseUtil.fail(GOODS_NOT_EXIST, "商品不存在");
        }
        if (null != shopId) {
            if (shopId != goods.getShopId()) {
                return ResponseUtil.fail(GOODS_UPDATE_NOT_ALLOWED, "商品允许修改");
            }
        }
/*        LitemallGoods updateData = new LitemallGoods();
        updateData.setId(price.getId());
        updateData.setRetailPrice(price.getPrice());*/
        LitemallGoodsProduct product = new LitemallGoodsProduct();
        product.setGoodsId(price.getId());
        product.setSellPrice(price.getPrice());
        productService.updateByGoodsId(product);
        return ResponseUtil.ok();
    }

    /**
     * 更新规格价格
     * 修改规格价格
     *
     * @param price  价格
     * @param shopId 商店id
     * @return {@link Object}
     */
    public Object updateSpecPrice(PriceDto price, Integer shopId) {
        LitemallGoodsSpecification specification = specificationService.findById(price.getId());
        LitemallGoods goods = goodsService.findById(specification.getGoodsId());
        if (null == goods) {
            return ResponseUtil.fail(GOODS_NOT_EXIST, "商品不存在");
        }
        if (null != shopId) {
            if (shopId != goods.getShopId()) {
                return ResponseUtil.fail(GOODS_UPDATE_NOT_ALLOWED, "商品不允许修改");
            }
        }
        LitemallGoodsSpecification updateData = new LitemallGoodsSpecification();
        updateData.setId(price.getId());
        updateData.setPrice(price.getPrice());
        specificationService.updateById(updateData);
        return ResponseUtil.ok();
    }

    /**
     * 更新存储
     * 修改规格数量
     *
     * @param storeDto 商店dto
     * @param shopId   商店id
     * @return {@link Object}
     */
    public Object updateStore(GoodsStoreDto storeDto, Integer shopId) {
//        LitemallGoodsProduct product = productService.findById(storeDto.getId());
        LitemallGoods goods = goodsService.findById(storeDto.getId());
        if (null == goods) {
            return ResponseUtil.fail(GOODS_NOT_EXIST, "商品不存在");
        }
        if (null != shopId) {
            if (shopId != goods.getShopId()) {
                return ResponseUtil.fail(GOODS_UPDATE_NOT_ALLOWED, "商品不允许修改");
            }
        }
        LitemallGoodsProduct updateData = new LitemallGoodsProduct();
        updateData.setGoodsId(goods.getId());
//        updateData.setId(storeDto.getId());
        updateData.setNumber(storeDto.getNumber());
        productService.updateByGoodsId(updateData);
        return ResponseUtil.ok();
    }

    /**
     * 所有价格
     * 查询商品的所有价格
     *
     * @param goodsId 商品id
     * @param shopId  商店id
     * @return {@link Object}
     */
    public Object allPrice(Integer goodsId, Integer shopId) {
        LitemallGoods goods = goodsService.findById(goodsId);
        if (null != shopId) {
            if (goods.getShopId() != shopId) {
                return ResponseUtil.fail(GOODS_NOT_PERMISSION, "无权处理该商品");
            }
        }
        List<LitemallGoodsProduct> litemallGoodsProducts = productService.queryByGid(goods.getId());
        List<LitemallGoodsSpecification> litemallGoodsSpecifications = specificationService.queryByGid(goodsId);
        List<LitemallGoodsLadderPrice> litemallGoodsLadderPrices = goodsLadderPriceService.queryByGoodsId(goods.getId());
        List<LitemallGoodsMaxMinusPrice> litemallGoodsMaxMinusPrices = goodsMaxMinusPriceService.queryByGoodsId(goods.getId());
        LitemallVipGoodsPrice litemallVipGoodsPrice = vipGoodsService.queryByGoodsId(goods.getId());
        GoodsPriceVo vo = new GoodsPriceVo();
        vo.setSpecifications(litemallGoodsSpecifications);
        vo.setId(goods.getId());
        vo.setGoodsName(goods.getName());
        vo.setGoodsSn(goods.getGoodsSn());
        vo.setPriceType(goods.getPriceType());
        if (litemallGoodsProducts.size() > 0) {
            vo.setGoodsSellPrice(litemallGoodsProducts.get(0).getSellPrice());
        }
        if (litemallVipGoodsPrice != null) {
            vo.setVipGoodsPrice(litemallVipGoodsPrice);
        }
        if (litemallGoodsLadderPrices.size() > 0) {
            vo.setLadderPrices(litemallGoodsLadderPrices);
        }
        if (litemallGoodsMaxMinusPrices.size() > 0) {
            vo.setMaxMinusPrices(litemallGoodsMaxMinusPrices);
        }
        return ResponseUtil.ok(vo);
    }

    /**
     * 查询vip商品价格
     * 根据商品ID 查询商品会员价格
     *
     * @param goodsId 商品id
     * @return {@link Object}
     */
    public Object queryVipGoodsPrice(Integer goodsId) {
        return vipGoodsService.queryByGoodsId(goodsId);
    }

    /**
     * 更新vip商品价格
     * 根据商品ID 修改商品会员价格
     *
     * @param vipGoodsPrice vip商品价格
     * @return {@link Object}
     */
    public Object updateVipGoodsPrice(LitemallVipGoodsPrice vipGoodsPrice) {
        if (ObjectUtils.isEmpty(vipGoodsPrice.getGoodsId())) {
            return ResponseUtil.fail(PromptEnum.P_101.getCode(), PromptEnum.P_101.getDesc());
        }
        return vipGoodsService.updateByGoodsId(vipGoodsPrice);
    }

    /**
     * 更新折扣价格
     * 根据商品ID 修改商品优惠价格
     *
     * @param goodsAllinone 货物allinone
     * @return {@link Object}
     */
    @Transactional
    public Object updateDiscountPrice(GoodsAllinone goodsAllinone) {
        if (goodsAllinone.getGoods() == null || ObjectUtils.isEmpty(goodsAllinone.getGoods().getId())) {
            return ResponseUtil.badArgument();
        }
        LitemallGoods goods = new LitemallGoods();
        goods.setId(goodsAllinone.getGoods().getId());
        goods.setPriceType(goodsAllinone.getGoods().getPriceType());

        if (goodsAllinone.getGoods().getPriceType() == 1) {
            goodsMaxMinusPriceService.deleteByGoodsId(goodsAllinone.getGoods().getId());
            goodsLadderPriceService.deleteByGoodsId(goodsAllinone.getGoods().getId());
            if (goodsAllinone.getVipPrice() != null) {
                goodsAllinone.getVipPrice().setGoodsId(goodsAllinone.getGoods().getId());
                vipGoodsService.updateByGoodsId(goodsAllinone.getVipPrice());
            }
            //满减价格和阶梯价格是先删除再添加
        } else if (goodsAllinone.getGoods().getPriceType() == 2 || goodsAllinone.getGoods().getPriceType() == 3) {
            goodsMaxMinusPriceService.deleteByGoodsId(goodsAllinone.getGoods().getId());
            vipGoodsService.deleteByGoodsId(goodsAllinone.getGoods().getId());
            goodsLadderPriceService.deleteByGoodsId(goodsAllinone.getGoods().getId());
            if (goodsAllinone.getLadderPrices() != null && goodsAllinone.getLadderPrices().length > 0) {
                for (LitemallGoodsLadderPrice price : goodsAllinone.getLadderPrices()) {
                    price.setGoodsId(goodsAllinone.getGoods().getId());
                    goodsLadderPriceService.add(price);
                }
            }
            if (goodsAllinone.getMaxMinusPrices() != null && goodsAllinone.getMaxMinusPrices().length > 0) {
                for (LitemallGoodsMaxMinusPrice price : goodsAllinone.getMaxMinusPrices()) {
                    price.setGoodsId(goodsAllinone.getGoods().getId());
                    goodsMaxMinusPriceService.add(price);
                }
            }
        } else {
            return ResponseUtil.badArgument();
        }
        goodsService.updateById(goods);
        return ResponseUtil.ok();
    }

    /**
     * 阅读产品产品
     *
     * @param goodsId 商品id
     * @param shopId  商店id
     * @return {@link Object}
     */
    public Object readGoodsProduct(Integer goodsId, Integer shopId) {
        return ResponseUtil.ok(productService.queryByGidAndSid(goodsId, shopId));
    }

    /**
     * 添加商品产品
     *
     * @param dto dto
     * @return {@link Object}
     */
    public Object addGoodsProduct(GoodsProductDto dto) {
        LitemallGoodsProduct product = new LitemallGoodsProduct();
        BeanUtils.copyProperties(dto, product);
        productService.add(product);
        return ResponseUtil.ok();
    }

    /**
     * 更新商品产品
     *
     * @param dto dto
     * @return {@link Object}
     */
    public Object updateGoodsProduct(GoodsProductDto dto) {
        if (dto.getId() == null) {
            return ResponseUtil.badArgument();
        }
        LitemallGoodsProduct product = new LitemallGoodsProduct();
        BeanUtils.copyProperties(dto, product);
        productService.updateById(product);
        return ResponseUtil.ok();
    }

    /**
     * 得到货物vos
     *
     * @param goodsList 商品列表
     * @param goodsVos  货物vos
     * @param shopId    商店id
     */
    private void getGoodsVos(List<LitemallGoods> goodsList, List<GoodsVo> goodsVos, Integer shopId) {
        if (!CollectionUtils.isEmpty(goodsList)) {
            goodsList.stream().forEach(goods -> {
                GoodsVo goodsVo = new GoodsVo();
                BeanUtils.copyProperties(goods, goodsVo);
                //库存查询
                List<LitemallGoodsProduct> litemallGoodsProducts = productService.queryByGidAndSid(goodsVo.getId(), shopId);
                if (litemallGoodsProducts.size() > 0) {
                    goodsVo.setNumber(litemallGoodsProducts.stream().mapToInt(goodsProduct -> goodsProduct.getNumber()).sum());
                    /**
                     * 这里默认取第一个价格
                     */
                    goodsVo.setRetailPrice(litemallGoodsProducts.get(0).getSellPrice());
                }
                //销量查询
               /* List<LitemallOrderGoods> litemallOrderGoods = orderGoodsService.queryByGidAndSid(goods.getId(), shopId);
                if (!CollectionUtils.isEmpty(litemallOrderGoods)) {
                    goodsVo.setSales(litemallOrderGoods.stream().mapToInt(adminOrderGoods -> adminOrderGoods.getNumber()).sum());
                }*/
                goodsVo.setSales(orderGoodsService.getGoodsSales(goods.getId(), shopId));
                goodsVo.setEditable(false);
                goodsVos.add(goodsVo);
            });
        }
    }

    /**
     * 让商店货物vos
     *
     * @param shops 商店
     * @return {@link List}<{@link GoodsVo}>
     */
    private List<GoodsVo> getShopGoodsVos(List<Map<String, Object>> shops) {
        List<GoodsVo> goodsVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(shops)) {
            goodsVos = JSONObject.parseArray(JSON.toJSONString(shops), GoodsVo.class);
            goodsVos.stream().forEach(goodsVo -> {
                //查询销量中商品销量
                List<LitemallOrderGoods> litemallOrderGoods = orderGoodsService.findByShopIdAndGoodsid(goodsVo.getShopId(), goodsVo.getId());
                if (!CollectionUtils.isEmpty(litemallOrderGoods)) {
                    goodsVo.setSales(litemallOrderGoods.stream().mapToInt(adminOrderGoods -> adminOrderGoods.getNumber()).sum());
                }
            });
        }
        return goodsVos;
    }

    /**
     * 所有
     * 根据门店查询id和名称options
     *
     * @param shopId 商店id
     * @return {@link Object}
     */
    public Object all(Integer shopId) {
        return ResponseUtil.ok(goodsService.queryByShopId(shopId));
    }

    /**
     * 规范mer列表
     * 查询已选择规格原料
     *
     * @param merchandiseId 商品id
     * @param specId        规范标识
     * @return {@link Object}
     */
    public Object specMerList(Integer merchandiseId, Integer specId) {
        List<LitemallGoodsSpecificationMerchandise> specificationMerchandises = specificationMerchandiseService.queryBySpecid(specId);
        List<Integer> selectedMerchandises = Optional.ofNullable(specificationMerchandises)
                .orElse(Collections.emptyList())
                .stream()
                .map(LitemallGoodsSpecificationMerchandise::getMerchandiseId)
                .collect(Collectors.toList());

        if (merchandiseId != null) {
            selectedMerchandises.remove(merchandiseId);
        }
        List<LitemallMerchandise> merchandises = merchandiseService.queryNotInMerchandiseIds(selectedMerchandises);
        return ResponseUtil.ok(merchandises);
    }

    /**
     * 添加规范
     *
     * @param goodsSpecAddDto 商品规格添加dto
     * @return {@link Object}
     */
    @Transactional
    public Object addSpec(GoodsSpecAddDto goodsSpecAddDto) {
        //删除配方关联商品
        lumiereGoodsFormulaCorrelationService.remove(new LambdaQueryWrapper<LumiereGoodsFormulaCorrelation>().eq(LumiereGoodsFormulaCorrelation::getGoodsId,goodsSpecAddDto.getGoodsId()));
        //添加商品
        LitemallGoodsSpecification goodsSpecification = new LitemallGoodsSpecification();
        BeanUtils.copyProperties(goodsSpecAddDto, goodsSpecification);
        specificationService.add(goodsSpecification);
        return ResponseUtil.ok(goodsSpecification);
    }

    /**
     * 更新规格
     *
     * @param goodsSpecAddDto 商品规格添加dto
     * @return {@link Object}
     */
    @Transactional
    public Object updateSpec(GoodsSpecAddDto goodsSpecAddDto) {
        Integer id = goodsSpecAddDto.getId();
        if (null == id) {
            return ResponseUtil.badArgument();
        }
        LitemallGoodsSpecification goodsSpecification = specificationService.findById(id);
        if (null == goodsSpecification) {
            return ResponseUtil.fail(GOODS_SPEC_NOT_EXIST, "商品规格不存在或已被删除");
        }
        BeanUtils.copyProperties(goodsSpecAddDto, goodsSpecification);
        specificationService.updateById(goodsSpecification);
        return ResponseUtil.ok(goodsSpecification);
    }

    /**
     * 删除规范
     *
     * @param specId 规范标识
     * @return {@link Object}
     */
    @Transactional
    public Object deleteSpec(Integer specId) {
        if (null == specId) {
            return ResponseUtil.badArgument();
        }

        //查询规格id是否已被使用，如被使用，不可删除
        Integer[] specIds = {specId};
       // boolean isCartExist = cartService.checkSpecIdExist(specIds);//查询购物车中是否存在
        boolean isCartExist =true;
        boolean isOrderExist = orderGoodsService.checkSpecIdExist(specIds);//查询订单中是否存在
        if (isCartExist || isOrderExist) {
            return ResponseUtil.fail(GOODS_SPEC_DELETE_NOT_ALLOWED, "商品规格已被使用，不可删除");
        }

        specificationService.deleteById(specId);
        return ResponseUtil.ok();
    }

    /**
     * 添加规范mer
     *
     * @param goodsMerchandiseDto 货物商品dto
     * @return {@link Object}
     */
    @Transactional
    public Object addSpecMer(GoodsMerchandiseDto goodsMerchandiseDto) {
        LitemallGoodsSpecificationMerchandise specificationMerchandise = new LitemallGoodsSpecificationMerchandise();
        BeanUtils.copyProperties(goodsMerchandiseDto, specificationMerchandise);
        specificationMerchandiseService.add(specificationMerchandise);

        goodsMerchandiseDto.setId(specificationMerchandise.getId());
        setMerchandiseDetail(goodsMerchandiseDto, specificationMerchandise.getMerchandiseId());
        return ResponseUtil.ok(goodsMerchandiseDto);
    }

    /**
     * 更新规范mer
     *
     * @param goodsMerchandiseDto 货物商品dto
     * @return {@link Object}
     */
    @Transactional
    public Object updateSpecMer(GoodsMerchandiseDto goodsMerchandiseDto) {
        Integer id = goodsMerchandiseDto.getId();
        if (null == id) {
            return ResponseUtil.badArgument();
        }
        LitemallGoodsSpecificationMerchandise specificationMerchandise = specificationMerchandiseService.findById(id);
        if (null == specificationMerchandise) {
            return ResponseUtil.fail(GOODS_SPEC_MER_NOT_EXIST, "商品规格原料不存在或已被删除");
        }
        BeanUtils.copyProperties(goodsMerchandiseDto, specificationMerchandise);
        specificationMerchandiseService.update(specificationMerchandise);

        setMerchandiseDetail(goodsMerchandiseDto, goodsMerchandiseDto.getMerchandiseId());
        return ResponseUtil.ok(goodsMerchandiseDto);
    }

    /**
     * 删除规范mer
     *
     * @param specMerId 规范mer id
     * @return {@link Object}
     */
    @Transactional
    public Object deleteSpecMer(Integer specMerId) {
        if (null == specMerId) {
            return ResponseUtil.badArgument();
        }

        specificationMerchandiseService.deleteById(specMerId);
        return ResponseUtil.ok();
    }


    /**
     * 添加附件
     * 新增辅料
     *
     * @param goodsAccessoryDto 商品附件dto
     * @return {@link Object}
     */
    @Transactional
    public Object addAccessory(GoodsAccessoryDto goodsAccessoryDto) {
        LitemallGoodsAccessory accessory = new LitemallGoodsAccessory();
        BeanUtils.copyProperties(goodsAccessoryDto, accessory);

        //判断组名是否已经被添加
        String accessoryGroupName = goodsAccessoryDto.getAccessoryGroupName();
        List<LitemallGoodsAccessoryGroup> groups = litemallGoodsAccessoryGroupService.findBySameName(accessoryGroupName, goodsAccessoryDto.getGoodsId());
        LitemallGoodsAccessoryGroup group = null;
        if (groups.size() > 0) {
            group = groups.get(0);
        } else {
            //新增
            group = new LitemallGoodsAccessoryGroup();
            group.setName(accessoryGroupName);
            group.setGoodsId(goodsAccessoryDto.getGoodsId());
            litemallGoodsAccessoryGroupService.add(group);
        }

        accessory.setAccessoryGroupId(group.getId());
        accessory.setAccessoryGroupName(goodsAccessoryDto.getAccessoryGroupName());
        accessoryService.add(accessory);

        goodsAccessoryDto.setId(accessory.getId());
        LitemallMerchandise merchandise = merchandiseService.findById(accessory.getMerchandiseId());
        goodsAccessoryDto.setMerchandiseSn(merchandise.getMerchandiseSn());
        goodsAccessoryDto.setModel(merchandise.getModel());
        goodsAccessoryDto.setStandard(merchandise.getStandard());
        goodsAccessoryDto.setBasicUnit(merchandise.getBasicUnit());
        return ResponseUtil.ok(goodsAccessoryDto);
    }

    /**
     * 更新附件
     * 修改辅料
     *
     * @param goodsAccessoryDto 商品附件dto
     * @return {@link Object}
     */
    @Transactional
    public Object updateAccessory(GoodsAccessoryDto goodsAccessoryDto) {
        Integer id = goodsAccessoryDto.getId();
        if (null == id) {
            return ResponseUtil.badArgument();
        }
        LitemallGoodsAccessory accessory = accessoryService.findById(id);
        if (null == accessory) {
            return ResponseUtil.fail(GOODS_ACCESSORY_NOT_EXIST, "商品辅料不存在或已被删除");
        }
        LitemallGoodsAccessoryGroup group = null;
        if (goodsAccessoryDto.getGroupName() != null) {
            List<LitemallGoodsAccessoryGroup> groups = litemallGoodsAccessoryGroupService.findBySameName(goodsAccessoryDto.getAccessoryGroupName(), goodsAccessoryDto.getGoodsId());
            if (groups.size() > 0) {
                group = groups.get(0);
            } else {
                group = new LitemallGoodsAccessoryGroup();
                group.setName(goodsAccessoryDto.getAccessoryGroupName());
                group.setGoodsId(goodsAccessoryDto.getGoodsId());
                litemallGoodsAccessoryGroupService.add(group);
            }
        }
        if (group != null) {
            accessory.setAccessoryGroupId(group.getId());
        }
        BeanUtils.copyProperties(goodsAccessoryDto, accessory);
        accessory.setAccessoryGroupName(goodsAccessoryDto.getAccessoryGroupName());
        accessoryService.update(accessory);


        LitemallMerchandise merchandise = merchandiseService.findById(accessory.getMerchandiseId());
        goodsAccessoryDto.setMerchandiseSn(merchandise.getMerchandiseSn());
        goodsAccessoryDto.setModel(merchandise.getModel());
        goodsAccessoryDto.setStandard(merchandise.getStandard());
        goodsAccessoryDto.setBasicUnit(merchandise.getBasicUnit());
        return ResponseUtil.ok(goodsAccessoryDto);
    }

    /**
     * 删除附件
     * 删除辅料
     *
     * @param accessoryId 附件标识
     * @return {@link Object}
     */
    @Transactional
    public Object deleteAccessory(Integer accessoryId) {
        if (null == accessoryId) {
            return ResponseUtil.badArgument();
        }

        //查询辅料id是否已被使用，如被使用，不可删除
        boolean isCartExist = cartGoodsAccessoryService.checkAccessoryIdExist(accessoryId);//查询购物车中是否存在
        boolean isOrderExist = orderGoodsAccessoryService.checkAccessoryIdExist(accessoryId);//查询订单中是否存在
        if (isCartExist || isOrderExist) {
            return ResponseUtil.fail(GOODS_ACCESSORY_DELETE_NOT_ALLOWED, "商品辅料已被使用，不可删除");
        }

        accessoryService.deleteById(accessoryId);
        return ResponseUtil.ok();
    }

    /**
     * 附件mer列表
     * 查询已选择辅料原料
     *
     * @param name          名字
     * @param merchandiseSn 商品sn
     * @return {@link Object}
     */
    public Object accessoryMerList(String name, String merchandiseSn) {
        List<LitemallMerchandise> merchandises = merchandiseService.querySelective(name, merchandiseSn);
        return ResponseUtil.ok(merchandises);
    }

    /**
     * 添加属性
     * 新增属性
     *
     * @param goodsPropertyDto 商品属性dto
     * @return {@link Object}
     */
    @Transactional
    public Object addProperty(GoodsPropertyDto goodsPropertyDto) {
        if(StrUtil.isBlank(goodsPropertyDto.getIsDefault())){
            goodsPropertyDto.setIsDefault(goodsPropertyDto.getValues()[0]);
        }
        LitemallGoodsProperty litemallGoodsProperty = new LitemallGoodsProperty();
        BeanUtils.copyProperties(goodsPropertyDto, litemallGoodsProperty);
        goodsPropertyService.add(litemallGoodsProperty);
        return ResponseUtil.ok(litemallGoodsProperty);
    }

    /**
     * 更新属性
     * 修改属性
     *
     * @param goodsPropertyDto 商品属性dto
     * @return {@link Object}
     */
    @Transactional
    public Object updateProperty(GoodsPropertyDto goodsPropertyDto) {
        Integer id = goodsPropertyDto.getId();
        if (null == id) {
            return ResponseUtil.badArgument();
        }

        LitemallGoodsProperty litemallGoodsProperty = goodsPropertyService.findById(id);
        if (null == litemallGoodsProperty) {
            return ResponseUtil.fail(GOODS_PROP_NOT_EXIST, "商品属性不存在或已被删除");
        }
        BeanUtils.copyProperties(goodsPropertyDto, litemallGoodsProperty);
        goodsPropertyService.update(litemallGoodsProperty);
        return ResponseUtil.ok(litemallGoodsProperty);
    }

    /**
     * 删除属性
     *
     * @param propertyId 属性id
     * @return {@link Object}
     */
    @Transactional
    public Object deleteProperty(Integer propertyId) {
        if (null == propertyId) {
            return ResponseUtil.badArgument();
        }

        //查询辅料id是否已被使用，如被使用，不可删除
        boolean isCartExist = cartGoodsPropertyService.checkPropertyIdExist(propertyId);//查询购物车中是否存在
        boolean isOrderExist = orderGoodsPropertyService.checkPropertyIdExist(propertyId);//查询订单中是否存在
    	/*if(isCartExist || isOrderExist) {
    		return ResponseUtil.fail(GOODS_PROP_DELETE_NOT_ALLOWED, "商品属性已被使用，不可删除");
    	}*/

        goodsPropertyService.deleteById(propertyId);
        return ResponseUtil.ok();
    }

    /**
     * 复制
     * 复制商品
     *
     * @param id     id
     * @param shopId 商店id
     * @return {@link Object}
     */
    @Transactional
    public Object copy(Integer id, Integer shopId) {
        LitemallGoods originGoods = goodsService.findById(id);
        if (null == originGoods) {
            return ResponseUtil.fail(GOODS_NOT_EXIST, "商品不存在");
        }
        LitemallGoods goods = new LitemallGoods();
        BeanUtils.copyProperties(originGoods, goods);
        // 商品基本信息表litemall_goods
        goods.setId(null);
        goods.setName(originGoods.getName() + "_copy");
        goods.setIsNew(false);
        goods.setIsHot(false);
        goods.setIsOnSale(false);
        goods.setReviewType(Constants.GOODS_REVIEW_PENDING.byteValue());//未审核
        goodsService.add(goods);
        saveGoodsLog(goods, Constants.CREATE_GOODS);
        //将生成的分享图片地址写入数据库
        String url = qCodeService.createGoodShareImage(goods.getId().toString(), goods.getPicUrl(), goods.getName());
        if (!StringUtils.isEmpty(url)) {
            goods.setShareUrl(url);
            if (goodsService.updateById(goods) == 0) {
                throw new RuntimeException("更新数据失败");
            }
        }

        Integer goodsId = goods.getId();
        //总部商品时
        if (null == originGoods.getShopId()) {
            List<LitemallGoodsRegion> regions = regionService.queryByGid(id);
            //添加商品区域
            for (LitemallGoodsRegion goodsRegion : regions) {
                LitemallGoodsRegion litemallGoodsRegion = new LitemallGoodsRegion();
                BeanUtils.copyProperties(goodsRegion, litemallGoodsRegion);
                litemallGoodsRegion.setId(null);
                litemallGoodsRegion.setGoodsId(goodsId);
                regionService.add(litemallGoodsRegion);
            }
        }

        // 商品规格表litemall_goods_specification
        List<LitemallGoodsSpecification> specifications = specificationService.queryByGid(id);
        for (LitemallGoodsSpecification goodsSpecification : specifications) {
            LitemallGoodsSpecification spec = new LitemallGoodsSpecification();
            BeanUtils.copyProperties(goodsSpecification, spec);
            spec.setId(null);
            spec.setGoodsId(goodsId);
            specificationService.add(spec);

            //规格原料
            Integer goodsSpecificationId = spec.getId();
            List<LitemallGoodsSpecificationMerchandise> goodsSpecificationMerchandises = specificationMerchandiseService.queryBySpecid(goodsSpecification.getId());
            for (LitemallGoodsSpecificationMerchandise goodsSpecificationMerchandise : goodsSpecificationMerchandises) {
                LitemallGoodsSpecificationMerchandise litemallGoodsSpecificationMerchandise = new LitemallGoodsSpecificationMerchandise();
                BeanUtils.copyProperties(goodsSpecificationMerchandise, litemallGoodsSpecificationMerchandise);
                litemallGoodsSpecificationMerchandise.setId(null);
                litemallGoodsSpecificationMerchandise.setGoodsId(goodsId);
                litemallGoodsSpecificationMerchandise.setGoodsSpecificationId(goodsSpecificationId);
                specificationMerchandiseService.add(litemallGoodsSpecificationMerchandise);
            }
        }

        // 商品参数表litemall_goods_attribute
        List<LitemallGoodsAttribute> attributes = attributeService.queryByGid(id);
        for (LitemallGoodsAttribute goodsAttribute : attributes) {
            LitemallGoodsAttribute attribute = new LitemallGoodsAttribute();
            BeanUtils.copyProperties(goodsAttribute, attribute);
            attribute.setId(null);
            attribute.setGoodsId(goodsId);
            attributeService.add(attribute);
        }

        //辅料表
        List<LitemallGoodsAccessory> litemallGoodsAccessories = accessoryService.queryByGoodsId(id);
        for (LitemallGoodsAccessory goodsAccessory : litemallGoodsAccessories) {
            LitemallGoodsAccessory accessory = new LitemallGoodsAccessory();
            BeanUtils.copyProperties(goodsAccessory, accessory);
            accessory.setId(null);
            accessory.setGoodsId(goodsId);
            accessoryService.add(accessory);
        }

        List<LitemallGoodsProperty> litemallGoodsProperties = goodsPropertyService.queryByGoodsId(id);
        for (LitemallGoodsProperty goodsProperty : litemallGoodsProperties) {
            LitemallGoodsProperty property = new LitemallGoodsProperty();

            BeanUtils.copyProperties(goodsProperty, property);
            property.setId(null);
            property.setGoodsId(goodsId);
            goodsPropertyService.add(property);
        }

        // vip价格
        LitemallVipGoodsPrice vipGoodsPrice = vipGoodsService.queryByGoodsId(id);
        if (null != vipGoodsPrice) {
            LitemallVipGoodsPrice vip = new LitemallVipGoodsPrice();
            BeanUtils.copyProperties(vipGoodsPrice, vip);
            vip.setId(null);
            vip.setGoodsId(goodsId);
            vip.setGoodsName(goods.getName());
            vipGoodsService.add(vip);
        }

        //阶梯价格
        List<LitemallGoodsLadderPrice> ladderPrices = goodsLadderPriceService.queryByGoodsId(id);
        if (null != ladderPrices && ladderPrices.size() > 0) {
            for (LitemallGoodsLadderPrice goodsLadderPrice : ladderPrices) {
                LitemallGoodsLadderPrice ladderPrice = new LitemallGoodsLadderPrice();
                BeanUtils.copyProperties(goodsLadderPrice, ladderPrice);
                ladderPrice.setId(null);
                ladderPrice.setGoodsId(goodsId);
                ladderPrice.setGoodsName(goods.getName());
                goodsLadderPriceService.add(ladderPrice);
            }
        }

        //满减价格
        List<LitemallGoodsMaxMinusPrice> maxMinusPrices = goodsMaxMinusPriceService.queryByGoodsId(id);
        if (null != maxMinusPrices && maxMinusPrices.size() > 0) {
            for (LitemallGoodsMaxMinusPrice goodsMaxMinusPrice : maxMinusPrices) {
                LitemallGoodsMaxMinusPrice maxMinusPrice = new LitemallGoodsMaxMinusPrice();
                BeanUtils.copyProperties(goodsMaxMinusPrice, maxMinusPrice);
                maxMinusPrice.setId(null);
                maxMinusPrice.setGoodsId(goodsId);
                maxMinusPrice.setGoodsName(goods.getName());
                goodsMaxMinusPriceService.add(maxMinusPrice);
            }
        }

        LitemallGoodsProduct product = new LitemallGoodsProduct();
        product.setShopId(shopId);
        product.setGoodsId(goods.getId());
        product.setUnit(goods.getUnit());
        product.setSellPrice(goods.getRetailPrice());
        product.setCostPrice(goods.getCounterPrice());
        productService.add(product);

        return detail(goodsId);
    }

    /**
     * 按关键字查询
     *
     * @param keyword 关键字
     * @return {@link Object}
     */
    public Object queryByKeyword(String keyword) {
        List<LitemallGoods> goods = goodsService.queryByKeyword(keyword);
        return goods.stream().map(good -> {
            GoodsVo vo = new GoodsVo();
            BeanUtils.copyProperties(good, vo);
            vo.setLabel(good.getName());
            return vo;
        }).collect(Collectors.toList());
    }

    public Object listpPutaway(Integer shopId) {
        List<LitemallGoods> litemallGoods = goodsMapper.selectList(Wrappers.lambdaQuery(LitemallGoods.class)
                .eq(LitemallGoods::getIsOnSale, 1)
                .orderByDesc(LitemallGoods::getAddTime));
        List<GoodsVo> goodsVos = new ArrayList<>();
        getGoodsVos(litemallGoods, goodsVos, shopId);
        return ResponseUtil.okList(goodsVos, litemallGoods);
    }

    public Object updateGoods(LitemallGoods goods) {
        return goodsMapper.updateById(goods) > 0 ? ResponseUtil.ok() : ResponseUtil.fail();
    }

    public Object categoryl3() {
        //获取当前所有商品的三级目录
        List<Integer> categoryIds = goodsMapper.selectList(null).stream().map(goods -> goods.getCategoryId()).distinct().collect(Collectors.toList());
        //获取名称
        List<AdminCategoryIdsDTO> dtoList = categoryIds.stream().map(categoryId -> {
            LitemallCategory category = categoryService.findById(categoryId);
            return AdminCategoryIdsDTO.builder()
                    .id(categoryId)
                    .name(category.getName())
                    .build();
        }).collect(Collectors.toList());
        return ResponseUtil.ok(dtoList);
    }

    public Object categoryThree() {
        //获取当前所有商品的三级目录
        List<Integer> categoryIds = goodsMapper.selectList(null).stream().map(LitemallGoods::getCategoryId).distinct().collect(Collectors.toList());
        List<LitemallCategory> categoryList = new ArrayList<>();
        categoryIds.forEach(categoryId -> categoryList.add(categoryService.findById(categoryId)));
        //获取名称
        List<AdminCategoryIdsDTO> dtoList = categoryList.stream().filter(category -> !category.getDeleted()).map(litemallCategory -> AdminCategoryIdsDTO.builder()
                .id(litemallCategory.getId())
                .name(litemallCategory.getName())
                .build()).collect(Collectors.toList());
        return ResponseUtil.ok(dtoList);

    }

    public Object categoryThreeLinkage() {
        return ResponseUtil.ok(categoryService.categoryThreeLinkage());
    }

    public Object generateGoodsSn() {
        // 查询当前最大的编号
        Integer maxGoodsSn = goodsMapper.findMaxGoodsSn();
        if (maxGoodsSn == null) {
            return ResponseUtil.ok(10000); // 初始值
        }
        return ResponseUtil.ok(maxGoodsSn + 1);
    }


}
